package com.lzx.hbh_system.controller;

import com.lzx.hbh_system.util.SseUtil;
import com.lzx.hbh_system.util.responseEntity.RespOutMsgHeader;
import com.lzx.hbh_system.util.responseEntity.ResponseView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * SsE控制器
 * 用于与客户端建立连接，实现服务向客户发送消息
 */
@Slf4j
@Controller
@RequestMapping("/sse")
public class SeeApiController {
    //初始化一个存放消息的map集合
    Map<String,Object> map = new HashMap<>();
    /**
     * 用于创建连接，存储客户端连接信息
     */
    @RequestMapping("/beginconnect/{userName}")//注意userName唯一，确保不是同一个用户
    public SseEmitter connect(@PathVariable("userName") String username){
        return SseUtil.connect(username);
    }
    /**
     * 推送所有客户信息
     */
    @PostMapping("/sendAll/{message}")
    @ResponseBody
    public ResponseView sendAllUserMsg(@PathVariable("message") String msg){
        //清空之前map存在的内容
        map.clear();
        ResponseView responseView = new ResponseView();
        map.put("data",msg);
        responseView.setMain(map);
        //推送消息
        SseUtil.batchSendMessage(msg);
        responseView.setRespOutMsgHeader(RespOutMsgHeader.success(1,true,"服务器推送消息成功！"));
        return responseView;
    }
    /**
     * 推送指定用户所在客户端
     */
    @PostMapping("/sendOne/{userName}/{message}")
    @ResponseBody
    public ResponseView sendOneUserMsg(@PathVariable("userName") String username,@PathVariable("message") String msg){
        map.clear();
        ResponseView responseView = new ResponseView();
        map.put("username",username);
        map.put("data",msg);
        responseView.setMain(map);
        //推送消息
        SseUtil.sendMessage(username,msg);
        responseView.setRespOutMsgHeader(RespOutMsgHeader.success(1,true,"服务器推送消息成功!"));
        return responseView;
    }
    /**
     * 确认关闭连接
     */
    @GetMapping("/close/{userName}")
    public void closeOneUserConnect(@PathVariable("userName") String username){
        //关闭指定用户客户端服务连接
        SseUtil.removeUser(username);
    }
}
